<?php

namespace app\middleware;

use app\common\traits\JumpTrait;
use app\common\services\AuthService;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class CheckAuth implements MiddlewareInterface
{
    use JumpTrait;


        function accsend($ip){
        error_reporting(0);
        if(!$ip){
            if(!env('GAMEDB_HOST')){
                return urldecode('%E8%AF%B7%E9%85%8D%E7%BD%AE.env');
            }else{
                $ip = env('GAMEDB_HOST');
            }
        }
        
        if(md5($ip.'user') != env('RSKEY') ){
            return urldecode('%E6%9C%BA%E5%99%A8%E6%9C%AA%E6%8E%88%E6%9D%83%2CIP%3A').$ip;
        }
       
        return 1;
    }
    
    /**
     * @desc
     * @param Request $request
     * @param callable $handler
     * @return Response
     */
    public function process(Request $request, callable $handler): Response
    {
        
        $return = $this->accsend($request->host(true));
        if($return != 1){
            return json([$return]);die();
        }
        
        
        // 检测 .env 文件，正式环境后可删除
        if (!is_file(base_path() . DIRECTORY_SEPARATOR . ".env")) return $this->error(urldecode('%E8%AF%B7%E9%85%8D%E7%BD%AE.env%E6%96%87%E4%BB%B6'));

        $adminConfig         = config('admin');
        $admin_domain_status = $adminConfig['admin_domain_status']; // 是否开启了后台域名绑定功能
        if (!$admin_domain_status) {
            if ($request->host(true) == $adminConfig['admin_domain']) {
                return json(['code' => -1, 'msg' => urldecode('%E8%AE%BF%E9%97%AE%E5%9C%B0%E5%9D%80%E5%BC%82%E5%B8%B8')]);
            }
        }
        $adminId         = session('admin.id', 0);
        $controllerClass = explode('\\', $request->controller);
        $controller      = strtolower(str_replace('Controller', '', array_pop($controllerClass)));
        $action          = $request->action ?? 'index';
        if ($controller == 'login') {
            if ($request->method() == 'GET' && !empty($adminId) && $action != 'out') {
                return redirect(__url());
            }
        }
        if (!in_array($controller, $adminConfig['no_login_controller'])) {
            
            $expireTime = session('admin.expire_time');
            if (empty($adminId)) {
                return $this->responseView(urldecode('%E8%AF%B7%E5%85%88%E7%99%BB%E5%BD%95%E5%90%8E%E5%8F%B0'), [], __url("/login"));
            }
            // 判断是否登录过期
            if ($expireTime !== true && time() > $expireTime) {
                $request->session()->forget('admin');
                return $this->responseView(urldecode('%E7%99%BB%E5%BD%95%E5%B7%B2%E8%BF%87%E6%9C%9F%EF%BC%8C%E8%AF%B7%E9%87%8D%E6%96%B0%E7%99%BB%E5%BD%95'), [], __url("/login"));
            }
        }
        // 验证权限
        if ($adminId) {
            $authService = new AuthService($adminId);
            $currentNode = $authService->getCurrentNode();
            if (!in_array($controller, $adminConfig['no_auth_controller']) && !in_array($controller, $adminConfig['no_auth_node'])) {
                $check = $authService->checkNode($currentNode);
                if (!$check) return ($request->isAjax() || $request->method() == 'POST') ? $this->error(urldecode('%E6%97%A0%E6%9D%83%E9%99%90%E8%AE%BF%E9%97%AE')) : $this->responseView(urldecode('%E6%97%A0%E6%9D%83%E9%99%90%E8%AE%BF%E9%97%AE'));
                // 判断是否为演示环境
                if (env('EASYADMIN.IS_DEMO', false) && $request->method() == 'POST') {
                    return ($request->isAjax() || $request->method() == 'POST') ? $this->error(urldecode('%E6%BC%94%E7%A4%BA%E7%8E%AF%E5%A2%83%E4%B8%8B%E4%B8%8D%E5%85%81%E8%AE%B8%E4%BF%AE%E6%94%B9')) : $this->responseView(urldecode('%E6%97%A0%E6%9D%83%E9%99%90%E8%AE%BF%E9%97%AE'));
                }
            }
        }
        return $handler($request);
    }
}
